#!/bin/sh
# SVN Update Check
# TODO: add support for checking for updates with a regular, archived source release!
becho() {
	printf "\033[1m$@\033[0m\n"
}
bprintf() {
	printf "\033[1m$@\033[0m"
}
cerr() {
	if [ ! "$1" = "0" ];then
		becho "ERROR: Something went wrong. See the above output for details."
		exit 1
	fi
}

becho "Checking for updates to ndLua..."

LATEST_REV=`svn info -r HEAD | grep -i "Last Changed Rev" | cut -f4 -d' '`
cerr $?
CURRENT_REV=`svn info | grep -i "Last Changed Rev" | cut -f4 -d' '`
cerr $?

if [ ! "$CURRENT_REV" = "$LATEST_REV" ];then
	becho "It looks like there is an update available for ndLua. The current SVN revision"
	becho "is $CURRENT_REV, and the latest revision is $LATEST_REV. Update? Note that"
	becho "updating will remove all unversioned files and uncommitted changes."
	bprintf 'Update? [Y/n] '
	read resp
	case $resp in
		[Yy]*|"")
			becho "Updating SVN."
			becho " - Removing unversioned files..."
			svn status --no-ignore | grep '^\?' | sed 's/^\?      //' | xargs -Ixx rm -rf xx; cerr $?
			becho " - Reverting all local changes..."
			svn revert -R .
			becho " - Updating to the latest SVN..."
			svn update; cerr $?
			becho "SVN update complete."
			if [ "$1" = "CALLED_FROM_MAKEFILE" ];then
				becho "Please restart the build process for the update to take effect."
				exit 1
			fi
			;;
		[Nn]*)
			becho "Not updating SVN."
			;;
		*)
			becho "Invalid response - assuming no update at this time."
			;;
	esac
else
	# TODO: decide on whether any printing is necessary; i.e. should we
	# adopt a silent-no-noise-unless-there's-an-update model?
	becho "No updates found! (Current revision is $CURRENT_REV, latest revision is $LATEST_REV.)"
fi
